package com.ztesoft.web.common;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ztesoft.framework.log.ZTEsoftLogManager;
import com.ztesoft.framework.util.Utils;
import com.ztesoft.web.baseconfig.db.dao.DmPlanDao;
import com.ztesoft.web.baseconfig.db.po.DmSrcTablePO;
import com.ztesoft.web.baseconfig.db.po.SubTableDefinePO;
import com.ztesoft.web.common.customdb.dao.SubTableDefineCustomDao;
import com.ztesoft.web.common.exchange.ExchangeFunc;
import com.ztesoft.web.syncbaseinfo.service.BaseInfoService;


/**
 * @Description 分表查询
 * @author lin.weibin@zte.com.cn
 * @date 2015年8月6日 下午8:23:33
 * @since 1.0
 *
 */
@Service
public class SubTableDefine {

	@Autowired
	private SubTableDefineCustomDao subTableDefineCustomDao;
	
	@Autowired
	private BaseInfoService baseInfoService;
	
	@Autowired
	private ExchangeFunc exchangeFunc;
	
	@Autowired
	private DmPlanDao dmPlanDao;
	
	/**
	 * 日志
	 */
    private final static ZTEsoftLogManager LOGGER = ZTEsoftLogManager
            .getLogger(SubTableDefine.class);
    
    /**
     * 初始化分表数据
     * @param srcTablePo	主表对象
     * @param nodeId	{DM_PLAN.NODE_ID}所属系统模块标志
     * @return	分表集合
     */
	public List<String> initTableName(DmSrcTablePO srcTablePo, int nodeId, int planId) {
		List<String> list = new ArrayList<String>();
		// 系统标志获取
		nodeId = baseInfoService.getRootLevelSysModule(nodeId);
		
		if ("0".equals(srcTablePo.getSubFlag())) {
			list.add(srcTablePo.getTableName());
		} else if ("1".equals(srcTablePo.getSubFlag())) {
			//
			List<SubTableDefinePO> subDefineList = 
					subTableDefineCustomDao.selectBySrcId(srcTablePo.getSourceDataId());
			if (Utils.isEmpty(subDefineList)) {
				throw  new RuntimeException("分表定义查无数据");
			}
			return generateTableName(srcTablePo, subDefineList, nodeId, planId);
		}
		return list;
	}


	private List<String> generateTableName(DmSrcTablePO srcTablePo, List<SubTableDefinePO> subDefineList, int nodeId, int planId) {

		Date date = dmPlanDao.selectByPrimaryKey(planId).getCreateDate();
		StringBuilder sb = new StringBuilder();
//		DmFuncDefinePO dmFuncDefinePO;
		int dloop = 0;
		List<String> lis = new ArrayList<String>();
		List<String> list = new ArrayList<String>();
		for (SubTableDefinePO po : subDefineList) {
			if (po.getSubDefineType() == 0) {
				sb.append(po.getSubDefineValue()).append("_");
			} else if (po.getSubDefineType() == 1) {
//				dmFuncDefinePO = dmFuncDefineCustomDao.selectByFuncId(Integer.parseInt(po.getSubDefineValue()));
//				String funcMethod = dmFuncDefinePO.getFuncMethod();
//				sb.append("{").append(dloop++).append("}").append("_");
				Integer lowerInt = srcTablePo.getLowerOffset();//数据类型
				Integer upperInt = srcTablePo.getUpperOffset();
				switch (Integer.parseInt(po.getSubDefineValue())) {
					case 1://按本地网
						list = exchangeFunc.latnIdExchange(nodeId);
						break;
					case 2:// 按年月->往前偏移
						list = exchangeFunc.yearMonthExchange(date, upperInt, lowerInt);
						break;
					case 3://按年月日->往前偏移
						list = exchangeFunc.dateExchange(date, upperInt, lowerInt);
						break;
					case 4://按账期->往前偏移
						list = exchangeFunc.billingCycleExchange(date, upperInt, lowerInt);
						break;
					case 5://按客户分组
						list = exchangeFunc.custCategoryExchange(nodeId);
						break;
					case 6://按清单序列
						list = exchangeFunc.detailSeqExchange(nodeId);
						break;
					case 7://按进程号分组
						list = exchangeFunc.pidExchange(nodeId);
						break;
					default:
						break;
				}
				if (Utils.notEmpty(list)) {			
					sb.append("{").append(dloop++).append("}").append("_");
					lis.add(Utils.convertIdList2StringByComma(list));
				}
			}
		}
		//
		List<String> resultList = new ArrayList<String>();
		if (lis.size() != 0) {			
			String[] a0 = lis.get(0).split(",");
			for (int i = 1; i < lis.size() && lis.size()>=2; i++) {
				a0 = Utils.buildArr(a0, lis.get(i).split(","));
			}
			for (int i = 0; i < a0.length; i++) {
				resultList.add(Utils.fillStringByArgs(sb.substring(0, sb.length()-1), a0[i].split(",")));
			}
		} else {
			resultList.add(sb.substring(0, sb.length()-1));
		}
		LOGGER.info("\r\n|分表集合|:"+resultList);
		return resultList;
	}
	
	/**
	 * 获取从表名
	 * @param sourceDataId 配置表标志
	 * @param keyNames 字段名
	 * @param keyValues 字段值
	 * @return
	 */
	public String generateRefTableName(int sourceDataId, String[] keyNames, String[] keyValues) {
		List<SubTableDefinePO> subDefineList = subTableDefineCustomDao
				.selectBySrcId(sourceDataId);
		StringBuilder sb = new StringBuilder();
		for (SubTableDefinePO po : subDefineList) {
			if (po.getSubDefineType() == 0) {
				sb.append(po.getSubDefineValue()).append("_");
			} else if (po.getSubDefineType() == 1) {
				for (int i = 0; i < keyNames.length; i++) {
					if (keyNames[i].equals(po.getSubRefCol())) {
						if (Utils.isEmpty(po.getSubDefineValue())) {// 转化方法
							sb.append(keyValues[i] + "_");
						} else {
							switch (Integer.parseInt(po.getSubDefineValue())) {
							case 2:// 年月
								sb.append(keyValues[i].substring(0, 4)+ keyValues[i].substring(5, 7) + "_");
								break;
							case 3:// 年月日
								sb.append(keyValues[i].substring(0, 4)+ keyValues[i].substring(5, 7) + keyValues[i].substring(8, 10) + "_");
								break;
							default:
								sb.append(keyValues[i] + "_");
								break;
							}
						}
					}
				}
			}
		}
		return sb.substring(0, sb.length() - 1);
	}

//	/**
//	 * 	 * 分表可变部分-转换执行方法	
//	 * @param funcMethod	执行方法类	(dmFuncDefine的FUNC_METHOD字段值)
//	 * @param systemId	系统标志	(需要根据PLAN_ID查询出SYSTEM_ID)
//	 * @param startOffset	偏移上限	木有-传-1
//	 * @param endOffset	偏移下限	木有-传-1
//	 * @return	可变部分集合
//	 */
//	public String doExchange(String funcMethod, int systemId, int startOffset, int endOffset) {
//		return doExchangeMethod(funcMethod, systemId, startOffset, endOffset);
//	}
//	
//
//	@SuppressWarnings("unchecked")
//	private String doExchangeMethod(String funcMethod, int systemId, int startOffset, int endOffset) {
//		Object clazz = null;
//		Method method = null;
//		List<String> list = new ArrayList<String>();
//		if (systemId == 0) {//
//			systemId = -1;
//		}
//		try {
//			clazz = Class.forName(DMSConstant.EXCHANGE_FUNC).newInstance();//可以抽取出来
//			method = clazz.getClass().getMethod(funcMethod, Integer.class, Integer.class, Integer.class);
//			list = (List<String>) method.invoke(clazz, systemId, startOffset, endOffset);
//		} catch (Exception e) {
//			LOGGER.error("\r\n|转换方法异常|",e);
//		}
//		return Utils.convertIdList2StringByComma(list);
//	}

	public String initTableNameParam(DmSrcTablePO srcTablePo, int nodeId, int planId) {
		// 系统标志获取
		nodeId = baseInfoService.getRootLevelSysModule(nodeId);
		
		if ("1".equals(srcTablePo.getSubFlag())) {
			//
			List<SubTableDefinePO> subDefineList = 
					subTableDefineCustomDao.selectBySrcId(srcTablePo.getSourceDataId());
			return generateTableNameParam(srcTablePo, subDefineList, nodeId, planId);
		}
		return "-1";
	}
	
	private String generateTableNameParam(DmSrcTablePO srcTablePo, List<SubTableDefinePO> subDefineList, int nodeId, int planId) {

		Date date = dmPlanDao.selectByPrimaryKey(planId).getCreateDate();
		List<String> list = new ArrayList<String>();
		SubTableDefinePO po = subDefineList.get(0);
		if (po.getSubDefineType() == 1) {
			Integer lowerInt = srcTablePo.getLowerOffset();//数据类型
			Integer upperInt = srcTablePo.getUpperOffset();
			switch (Integer.parseInt(po.getSubDefineValue())) {
				case 1://按本地网
					list = exchangeFunc.latnIdExchange(nodeId);
					break;
				case 2:// 按年月->往前偏移
					list.add("2");
					break;
				case 3://按年月日->往前偏移
					list.add("1");
					break;
				case 4://按账期->往前偏移
					list = exchangeFunc.billingCycleExchange(date, upperInt, lowerInt);
					break;
				case 5://按客户分组
					list = exchangeFunc.custCategoryExchange(nodeId);
					break;
				case 6://按清单序列
					list = exchangeFunc.detailSeqExchange(nodeId);
					break;
				case 7://按进程号分组
					list = exchangeFunc.pidExchange(nodeId);
					break;
				default:
					break;
			}
		}
		return Utils.convertIdList2StringByComma(list);
	}
}
